package main

import (
	"fmt"
	"gitee.com/apinktara/common"
	"gitee.com/apinktara/payment/domain/repository"
	service2 "gitee.com/apinktara/payment/domain/service"
	"gitee.com/apinktara/payment/handler"
	product2 "gitee.com/apinktara/payment/proto/payment"
	"github.com/asim/go-micro/plugins/registry/consul/v3"
	"github.com/asim/go-micro/plugins/wrapper/monitoring/prometheus/v3"

	opentracing2 "github.com/asim/go-micro/plugins/wrapper/trace/opentracing/v3"
	"github.com/asim/go-micro/plugins/wrapper/ratelimiter/uber/v3"
	"github.com/asim/go-micro/v3"
	"github.com/asim/go-micro/v3/registry"
	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/mysql"
	"github.com/opentracing/opentracing-go"
)

var QPS =100

func main() {
	consulConfig, err := common.GetConsulConfig("127.0.0.1", 8500, "/micro/config")
	if err != nil {
		fmt.Println(err)
	}
	// 注册中心
	consulRegistry := consul.NewRegistry(func(options *registry.Options) {
		options.Addrs = []string{
			"127.0.0.1:8500",
		}
	})
	//数据库链接
	mysqlInfo := common.GetMysqlConsul(consulConfig, "mysql")
	db, err := gorm.Open("mysql", mysqlInfo.User+":"+mysqlInfo.Pwd+"@/"+mysqlInfo.Database+"?charset=utf8mb4&parseTime=true&loc=Local")
	if err != nil {
		fmt.Println(err)
	}
	defer db.Close()
	db.SingularTable(true)

	err = repository.NewPaymentRepository(db).InitTable()
	if err != nil {
		fmt.Println(err)
	}
	//链路追踪
	t, io, err := common.NewTracer("go.micro.service.payment", "127.0.0.1:6831")
	if err != nil {
		fmt.Println(err)
	}
	defer io.Close()
	opentracing.SetGlobalTracer(t)

	// 添加监控
	common.PrometheusBoot(9092)


	service := micro.NewService(
		micro.Name("go.micro.service.payment"),
		micro.Version("latest"),
		micro.Address("127.0.0.1:8089"),
		micro.Registry(consulRegistry),
		//链路追踪
		micro.WrapHandler(opentracing2.NewHandlerWrapper(opentracing.GlobalTracer())),
		// 添加限流
		micro.WrapHandler(ratelimit.NewHandlerWrapper(QPS)),
		// 添加监控
		micro.WrapHandler(prometheus.NewHandlerWrapper()),

	)
	cartDataService := service2.NewPaymentDataService(
		repository.NewPaymentRepository(db))

	service.Init()

	product2.RegisterPaymentHandler(service.Server(), &handler.Payment{
		PaymentDataService: cartDataService,
	})

	if err != nil {
		fmt.Println(err)
	}
	if err := service.Run(); err != nil {

		fmt.Println(err)
	}

}
